var inquiry_id = GetQueryString('inquiry_id');
//console.log("inquiry_id"+inquiry_id);
var state = GetQueryString("inquiry_status");
var matcher_id = GetQueryString('matcher_id');
var matching_name = JSON.parse(web.readCookie("loginData")).user.name;
var fix_price_id = GetQueryString('fix_price_id');
var fix_price_name = JSON.parse(web.readCookie("loginData")).user.name
var customer_id = GetQueryString('customer_id');
var receiver_province = GetQueryString('receiver_province');
var member_id=GetQueryString('member_id');
var platform = GetQueryString('platform');
var warehouse_code=""
var addintercepts=0
var verificationall=true
var customer_codes=""
let a=0,   //现货商品
    b=0,   //预售商品
    c=0;   //有码预售商品
function btnShow() {
    if (a==0){
        $('#existGoods').hide();
        $('#packAll').hide();
    } else {
        $('#existGoods').show();
    }
    if (b==0){
        $('#packAll').hide();
    }
    if (c==0){
        $('#packAll').hide();
        $('#onlyPreSale').hide();
    } else {
        $('#onlyPreSale').show();
    }
    if (a!=0&&c!=0){
        $('#packAll').show();
    }
    bool = true;
    console.log('现有数量：'+a)
    console.log('临采数量：'+b)
    console.log('临采有码数量：'+c)
    console.log('—————————华丽的分割线———————')
}
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
};
function  getState(state) {
    if(state=='10'||state=='20'){
        return '待匹配';
    }else if(state =='30'||state == '40'){
        return  '待定价';
    }else if(state == '50'){
        return '已报价';
    }else if(state == '60'){
        return '已退回';
    }else if(state == '70'){
        return '已撤销';
    }else if(state == '80'){
        return '已下单';
    };
}
//获取操作人的姓名及ID
var loginData = JSON.parse(web.readCookie("loginData"));
var service_name = loginData.user.name;
var service_id = loginData.user.user_ID;
// 询价单状态
$ ('#inquiry_status').text('询价单状态：'+getState(state));
// 商品基础信息
var baseParams = {
    "async": true,
    "crossDomain": true,
    "url": root.xunjiadan.getProductInfo,
    "method": "POST",
    "headers": {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    "data": {
        "inquiry_id": inquiry_id                             //询价单编号
    }
}

$.ajax(baseParams).done(function (result) {
    warehouse_code=result.warehouse_code;
    customer_codes=result.customer_code
    $('#inquiry_id').text(result.inquiry_id);
    $('#inquiry_name').text(result.inquiry_name);
    $('#created_time').text(result.created_time);
    $('#collect_address').text(result.receiver_province_name + '/' + result.receiver_city_name + '/' + result.receiver_area_name + '/' + result.detail_address+'/'+result.street_name);
    $('#linkman').text(result.linkman);
    $('#linkman_phone').text(result.linkman_phone);
    $('#customer_name').text(result.customer_name);
    $('#other_explain').text(result.other_explain);
    if(result.source==20){
        $('#platform').text("APP");
    }else {
        $('#platform').text("PC");
    }
    if(result.claim_arrival_time=="1000-01-01"){
        $('#timemin').val("");
    }else {
        $('#timemin').val(result.claim_arrival_time);
    }
    if(result.claim_purchase_time=="1000-01-01 00:00:00"){
        $('#timemax').val("");
    }else {
        $('#timemax').val(result.claim_purchase_time);
    }
});
// 报价单说明----------------------------------------------开始
var remarkParams = {
    "async": true,
    "crossDomain": true,
    "url": root.xunjiadan.inquiryQuotationExplain,
    "method": "POST",
    "headers": {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    "data": {
        "inquiryId": inquiry_id                          //询价单编号
    }
}
$.ajax(remarkParams).done(function (result) {
    if (result && result.length > 0) {
        $('#offer_table').show();
    } else {
        $('#offer_table').hide();
    }
    var html = '';
    for (var i = 0; i < result.length; i++) {
        html += '<tr>'
            + '<td>' + result[i].serviceName + '</td>'
            + '<td>' + result[i].quotationExplain + '</td>'
            + '<td>' + result[i].createTime + '</td>'
            + '<td id="' + result[i].id + '"></td>'
            + '</tr>'
    }
    ;
    $('#offer_list').empty().append(html);
});
//报价单说明 增加
$('#addoffer_value').click(function () {
    var result = $('#offer_value').val();
    if (result == "") {
        layer.msg('备注不能为空', {icon: 5, time: 1000});
        return false
    }
    var create_time = $.nowDate();
    var addRemParams = {
        "async": true,
        "crossDomain": true,
        "url": root.xunjiadan.addInquiryQuotationExplain,
        "method": "POST",
        "headers": {
            "Content-Type": "application/json"
        },
        "processData": false,
        "data": JSON.stringify({
            "belongInquiryId": inquiry_id,            //询价单编号
            "serviceId": service_id,
            "serviceName": service_name,
            // "create_time": create_time,
            "quotationExplain": result,
            "resultState":10
        })
    }
    //添加备注成功
    $.ajax(addRemParams).done(function (response) {
        $('#remarks').val('');
        if (response.code == '0') {
            $('#offer_table').show();
            $('#offer_list').append('<tr><td>' + response.serviceName + '</td><td>' + response.quotationExplain + '</td><td>' + response.createTime + '</td><td id="' + response.id + '"><a href="javascript:void(0);" class="deleteRemarks">删除</a></td></tr>');
            layer.msg('添加成功！', {icon: 6, time: 1000});
        } else {
            layer.msg(response.response, {icon: 5, time: 1000});
        }
    });
})
//删除 报价单说明
$('#offer_table').on('click', '.deleteRemarks', function () {
    var Result_id = $(this).parent('td').attr('id');
    var ele = $(this);
    var settings6 = {
        "async": true,
        "crossDomain": true,
        "url": root.xunjiadan.deleteInquiryQuotationExplain,
        "method": "POST",
        "headers": {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        "data": {
            "quotationExplainId": Result_id
        }
    }
    $.ajax(settings6).done(function (response) {
        if (response.code == '0') {
            layer.msg('删除成功', {icon: 6, time: 1000});
            ele.parents('tr').remove();
            if ($('#offer_list tr').length == 0) {
                $('#offer_table').hide();
            }
        } else {
            alert(response.message);
        }
    });
});
// 报价单说明----------------------------------------------结束
//备注
var remarkParams = {
    "async": true,
    "crossDomain": true,
    "url": root.xunjiadan.getRemarksList,
    "method": "POST",
    "headers": {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    "data": {
        "inquiry_id": inquiry_id                          //询价单编号
    }
}
//添加备注
$('#addRemarks').click(function () {
    var result = $('#remarks').val();
    var create_time = $.nowDate();
    if(result==''){
        layer.msg('备注不能为空！', {icon: 5,time:1000});
        return false;
    }
    var addRemParams = {
        "async": true,
        "crossDomain": true,
        "url": root.xunjiadan.addRemarks,
        "method": "POST",
        "headers": {
            "Content-Type": "application/json"
        },
        "processData": false,
        "data": JSON.stringify({
            "belong_inquiry_id": inquiry_id,            //询价单编号
            "service_id": service_id,
            "service_name": service_name,
            "create_time":create_time,
            "result":result
        })
    }

    $.ajax(addRemParams).done(function (response) {
        $('#remarks').val('');
        if (response.code == '0') {
            $('#remarkTable').show();
            $('#remarksList').append('<tr><td>'+response.service_name+'</td><td>'+response.result+'</td><td>'+response.create_time+'</td><td id="'+response.id+'"><!--<a href="javascript:void(0);" class="deleteRemarks">删除</a></td>--></tr>');
            layer.msg('添加成功！', {icon: 6,time:1000});
        }
    });
})
//删除备注
$('#remarkTable').on('click', '.deleteRemarks', function (){
    if(!confirm('确定是否删除？')){
        return false;
    }
    var Result_id = $(this).parent('td').attr('id');
    var ele = $(this);
    var settings6 = {
        "async": true,
        "crossDomain": true,
        "url": root.xunjiadan.deleteRemarks,
        "method": "POST",
        "headers": {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        "data": {
            "Result_id": Result_id
        }
    }
    //console.log(settings6);
    $.ajax(settings6).done(function (response) {
        if (response.code == '0') {
            layer.msg('删除成功！', {icon: 6,time:1000});
            ele.parents('tr').remove();
            if($('#remarksList tr').length == 0){
                $('#remarkTable').hide();
            }
        } else {
            alert(response.message);
        }
    });
});
$.ajax(remarkParams).done(function (result) {
    if(result.length>0){
        $('#remarkTable').show();
    }else{
        $('#remarkTable').hide();
    }
    var html = '';
    for (var i = 0; i < result.length; i++) {
        html += '<tr>'
            + '<td>' + result[i].service_name + '</td>'
            + '<td>' + result[i].result + '</td>'
            + '<td>' + result[i].create_time + '</td>'
            + '<td id="' + result[i].id + '"><!--<a href="javascript:void(0)" class="deleteRemarks">删除</a>--></td>'
            + '</tr>'
    }
    ;
    $('#remarksList').empty().append(html);
});
//商品附件
var fileParams = {
    "async": true,
    "crossDomain": true,
    "url": root.xunjiadan.getFileList,
    "method": "POST",
    "headers": {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    "data": {
        "inquiry_id": inquiry_id                          //询价单编号
    }
}

$.ajax(fileParams).done(function (result) {
    var html = '';
    for (var i = 0; i < result.length; i++) {
        if (result[i].file_name == '') {
            var urlName = result[i].file_path;
            var imgUrl = urlName.substring(0, urlName.indexOf('?'));
            result[i].file_name = imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
        }
        var strarea = result[i].file_name ;
        var po = strarea.split(".");//截取.xls前的字符串
        html += '<li>'
            + '<b>附件' + (i + 1) + ':</b>'
            + '<div style="margin-top: -20px;margin-left: 38px;height: 20px;position: relative;"><a href="' +root.xunjiadan.downLoadFromUrl+'?urlStr='+encodeURIComponent(result[i].file_path)+'&fileName='+encodeURIComponent(po[0])+ '">下载</a></div>'
            + '<div class="bg-grey" style="margin-left: 65px;position: relative;top: -25px;">'
            + '<span>' + result[i].file_name + '</span>'
            + '</div></li>';
    }
    $('#fujian').empty().append(html);
});
//商品清单
var productParams = {
    "async": true,
    "crossDomain": true,
    "url": root.xunjiadan.getProductList,//root.xunjiadan.getProductList,
    "method": "POST",
    "headers": {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    "data": {
        "inquiry_id": inquiry_id                          //询价单编号
    }
};

$.ajax(productParams).done(function (data) {
    console.log(data);
    if (data) {
        var html = '';
        /* let a=0,   //现货商品
             b=0,   //预售商品
             c=0;   //有码预售商品*/
        for (var i = 0; i < data.length; i++) {
            var pic = isProductError(data[i].product_depict,1);
            var desc =""
            var abnormal_type='';
            var current='';
            if(data[i].abnormal_type == 20){
                abnormal_type="异常询价"
                current='current'
             
            }else {
                abnormal_type=""
                current=''
              
            }


            desc = isProductError(data[i].product_depict);
            // if(JSON.parse(data[i].product_depict).desc!=null){
            //     desc = JSON.parse(data[i].product_depict).desc;
            // }else {
            //     desc =""
            // }
            if(data[i].claim_purchase_time == '1000-01-01'){
                var claim_purchase_time ='';
            }else{
                var claim_purchase_time =data[i].claim_purchase_time;
            }
            if(data[i].claim_arrival_time == '1000-01-01'){
                var claim_arrival_time ='';
            }else{
                var claim_arrival_time =data[i].claim_arrival_time;
            }
            if(data[i].sku_code==''||data[i].sku_code=='0'){ // 未匹配
                if(data[i].abnormal_type != 20){
                    var sku_name =  '<input  value ="'+data[i].sku_name+'"/>' //平台名称
                    var product_classify = '<input value ="'+data[i].product_classify+'"/>';//分类
                    var brand = '<input value ="'+data[i].brand+'"/>'; //品牌
                    var price = '<input value ="'+data[i].price+'"/>';  //成本价
                    /* var discount_price =  '<input value ="'+data[i].discount_price+'"/>';//价格*/
                    var discount_price = '<input class="disPrice" value ="'+data[i].discount_price+'" onblur="checkPrice(this);"/>';
                    var unit_name = '<input oninput="checkMaxIut(this)" value ="'+data[i].unit_name+'"/>'; //单位
                    var product_cycle = '<input value ="'+data[i].product_cycle+'"/>';//到货周期
                    var subtotal = data[i].subtotal;
                }else{
                    var sku_name = data[i].sku_name; //平台名称
                    var product_classify = data[i].product_classify; //分类
                    var brand = data[i].brand; //品牌
                    var price = data[i].price==0?'':data[i].price;  //成本价
                    var discount_price = data[i].discount_price; //价格
                    var unit_name = data[i].unit_name;  //单位
                    var product_cycle = data[i].product_cycle; //到货周期
                    var subtotal = data[i].subtotal; 
                }

                
            }else{//已匹配
                var sku_name = data[i].sku_name; //平台名称
                var product_classify = data[i].product_classify; //分类
                var brand = data[i].brand; //品牌
                var price = data[i].price==0?'':data[i].price;  //成本价
                var discount_price = data[i].discount_price; //价格
                var unit_name = data[i].unit_name;  //单位
                var product_cycle = data[i].product_cycle; //到货周期
                var subtotal = data[i].subtotal;
            }
            if(data[i].abnormal_type != 20){
               var numdata= '<div class="numberbar"><span onclick="number_decrease(this)" class="number_decrease">-</span><span onclick="number_increase(this)" class="number_increase">+</span><input id="Smallplan" maxlength="5" type="text" class="num_text Numberwo" value="'+data[i].product_count+'"></div>'
            }else{
              var numdata=  '<div class="numberbar">'+data[i].product_count+'</div>'
            }
            var explanation=""
            if(data[i].explanation==null){
                explanation=""
            }else {
                explanation=data[i].explanation
            }
            var abnormal_text=data[i].abnormal_text?data[i].abnormal_text:''
            html += '<tr class="idcans '+current+'" id="' + data[i].id + '" belong_inquiry_id="' + data[i].belong_inquiry_id + '">'
                + '<td class="xfqg_td1">' + (i + 1) + '</td>' //序号
                + '<td class="xfqg_td2" sku_id="' + data[i].sku_id + '" spu_id="' + data[i].spu_id + '">' + data[i].sku_code + '</td>' // spu sku skucode
                + '<td class="xfqg_td3">' + data[i].product_name + '</td>' //商品名称
                + '<td class="xfqg_td4">' + sku_name + '</td>' //平台商品名称
                + '<td class="xfqg_td5">' + product_classify + '</td>'  //分类
                + '<td class="xfqg_td6">' + brand + '</td>'     //品牌
                + '<td class="xfqg_td7">' + '<img style="width:24px;height:auto;" src="' + pic + '"/>' + desc + '</td>' //商品描述
                + '<td class="xfqg_td8">' + data[i].order_fillrates+ '</td>' //订货要求
                + '<td class="xfqg_td9" >' + price + '</td>' //成本价
                + '<td class="xfqg_td10" >' + discount_price + '</td>'//价格
                + '<td class="xfqg_td11">' +numdata + '</td>' //数量
                + '<td class="xfqg_td12">' + unit_name + '</td>' //单位
                + '<td class="xfqg_td13">' + subtotal + '</td>' //小计
                /*      + '<td class="xfqg_td14">' + claim_arrival_time + '</td>' //要求到货时间
                      + '<td class="xfqg_td15" created_time="' + data[i].created_time + '" update_time="' + data[i].update_time + '">' + claim_purchase_time + '</td>'*/ //要求采购时间
                + '<td class="xfqg_td16">'+product_cycle+'</td>'  //到货周期
                + '<td class="rfqg_td18">'+abnormal_type+'</td>'//异常询价
                + '<td class="rfqg_td18">'+abnormal_text+'</td>'//异常询价备注
                + '<td class="xfqg_td18"><span>'+explanation+'</span></td>';  //报价说明
       
            if (data[i].spu_id==0){
                b++
                if (data[i].sku_code!=''){
                    var HTML1=""
                    if(data[i].order_status=="20"){
                        HTML1='<td class="xfqg_td17 presale" info_state="'+data[i].info_state+'">' +
                            '<span>已下单</span></td>';
                    }else {
                    
                        HTML1+= '<td class="xfqg_td17 presale" info_state="'+data[i].info_state+'">' +
                            '<a class="delProduct" onclick="deleteData(3,this)" href =' +
                            ' "javascript:void(0);">删除</a></td>'
                    }
                    c++
                    html+= HTML1;
                } else {
                    var HTML2=""
                    if(data[i].order_status=="20"){
                        HTML2='<td class="xfqg_td17 presale" info_state="'+data[i].info_state+'">' +
                            '<span>已下单</span></td>';
                    }else {
                        HTML2= '<td class="xfqg_td17 temporary" info_state="'+data[i].info_state+'">' +
                            '<a class="delProduct" onclick="deleteData(2,this)" href =' +
                            ' "javascript:void(0);">删除</a></td>';
                    }
                    html+= HTML2
                    /*'<a class="matchProduct" onclick="matchProduct(2,this)"' +
                      /!*' href="javascript:void(0);">匹配商品</a>' +*!/*/
                }
            } else {
                a++;
                var HTML3=""
                if(data[i].order_status=="20"){
                    HTML3='<td class="xfqg_td17 presale" info_state="'+data[i].info_state+'">' +
                        '<span>已下单</span></td>';
                }else {
                    HTML3= '<td class="xfqg_td17 exist" info_state="'+data[i].info_state+'">'
                        +'<a class="delProduct" onclick="deleteData(1,this)" href = "javascript:void(0);">删除</a></td></td>';
                }
                html+= HTML3
                // '<a  class="matchProduct" onclick="matchProduct(1,this)"' +
                /*' href="javascript:void(0);">匹配商品</a>' +*/
                /*''*/
            }
            html+= '</tr>'

        };
        btnShow()
        $('#productList').empty().append(html);
        /*timeSet($('.xfqg_td14>input'));
        timeSet($('.xfqg_td15>input'));*/
    }
});

// 添加商品
// 添加已有商品
$('#addProduct').click(function () {
    url= 'addproducts.html?receiver_province='+receiver_province+'&platform='+platform+'&customer_id='+customer_id+'&member_id='+member_id+'&warehouse_code='+warehouse_code+'&customer_codes='+customer_codes;
    title = '添加商品';
    goNextPage(title, url);
});
// 返回后添加商品
function dataListAdd(product_count,skucodes){
    //console.log(product_count,skucodes);
    addProductBySkuCode('add',skucodes,product_count,'');
}
//匹配商品
/*$('#productList').on('click','.matchProduct',function () {
    var order = $(this).parents('tr').find('.xfqg_td1').text();
    var product_name = $(this).parents('tr').find('.xfqg_td3').text();
    var product_count = $(this).parents('tr').find('.xfqg_td11 input').val();
    var unit_name = $(this).parents('tr').find('.xfqg_td12').text();
    product_depict = $(this).parents('tr').find('.xfqg_td7').text();
    url  = "matchproducts.html?inquiry_id="+encodeURI(inquiry_id)+'&order='+order+'&product_name='+product_name+'&product_count='+product_count+'&unit_name='+unit_name+'&product_depict='+product_depict+'&receiver_province='+receiver_province+'&platform='+platform;
    title = "匹配商品";
    goNextPage(title, url)
});*/
function matchProduct(val,e){
    var order = $(e).parents('tr').find('.xfqg_td1').text();
    var product_name = $(e).parents('tr').find('.xfqg_td3').text();
    var product_count = $(e).parents('tr').find('.xfqg_td11 input').val();
    if(product_count==undefined){
        var product_count = $(e).parents('tr').find('.xfqg_td11').html();

    }
    var unit_name = $(e).parents('tr').find('.xfqg_td12').text();
    var id = $(e).parents('tr').attr('id');
    console.log(id);
    var product_depict = $(e).parents('tr').find('.xfqg_td7').text();
    window.sessionStorage.setItem('product_name',product_name);
    window.sessionStorage.setItem('unit_name',unit_name);
    window.sessionStorage.setItem('product_depict',product_depict);
    url  = "matchproducts.html?inquiry_id="+encodeURI(inquiry_id)+'&order='+order+'&product_name='+product_name+'&product_count='+product_count+'&unit_name='+unit_name+'&product_depict='+product_depict+'&receiver_province='+receiver_province+'&platform='+platform+'&product_kind='+val+'&skuOrder='+id+'&customer_id='+customer_id+'&customer_codes='+customer_codes+'&warehouse_code='+warehouse_code
    title = "匹配商品";
    goNextPage(title, url)
}
//返回后匹配商品
function datalsit(product_countMatch,skucodeMatch,order,val,skuOrder) {
    console.log(product_countMatch)
    console.log(skucodeMatch)
    console.log(order)
    console.log(val)
    console.log(skuOrder)

    addProductBySkuCode('match',skucodeMatch[0],product_countMatch,order,val,skuOrder);
}
// 删除商品  隐藏
function deleteData(e,target){
    //console.log(e)
    if (e==1){
        a--;
    } else if (e==2){
        b--;
    } else if (e==3){
        c--;
        b--;
    }
    btnShow()
    $(target).parent('td').attr('info_state','20');
    $(target).parents('tr').hide();
}
//完成添加
function addProductBySkuCode(oper,skucodes,product_count,order,val,skuOrder) {
    //a=0;b=0;c=0//重置现货、临采数量
    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.xunjiadan.searchSkuInfoDetailByPage,
        cache: false,  //禁用缓存
        dataType: "json",
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":10,
            "cityCode":receiver_province,
            "skuCode":skucodes,
            "warehouseId":warehouse_code,
            "memberId":member_id,
            "customerCode":customer_codes
        }),
        success: function (result) {
            //console.log(result);
            if(result.errorCode == '0') {
                var data = result.data.data[0];
                var html = '';
                //图片路径
                if (data.imgDtos) {
                    var img_url = data.imgDtos[0].imgUrl
                } else {
                    var img_url = '';
                }
                //价格
                if(data.salePrice){
                    var discountPrice = data.salePrice;
                }else{
                    var discountPrice =""
                }
                //小计
                var subtotal = (parseFloat(discountPrice) * parseInt(product_count)).toFixed(2);
                if (oper == 'add') { //添加
                    console.log('添加')
                    html += '<tr class="idcans" belong_inquiry_id="' + inquiry_id + '">'
                        + '<td class="xfqg_td1">' + ($('#productList tr').length+1) + '</td>'
                        + '<td class="xfqg_td2" sku_id="' + data.skuId + '" spu_id="' + data.spuId + '">' + data.skuCode + '</td>'
                        + '<td class="xfqg_td3">' + data.skuName+ ' </td>'
                        + '<td class="xfqg_td4">' + data.skuName+ ' </td>'
                        + '<td class="xfqg_td5">' + data.categoryName + '</td>'
                        + '<td class="xfqg_td6">' + data.brandName + '</td>'
                        + '<td class="xfqg_td7">' + '<img style="width:24px;height:auto;" src = "'+img_url+'"/>'+ data.skuName + '</td>'
                        + '<td class="xfqg_td8">' + '' + '</td>'
                        + '<td class="xfqg_td9" ></td>'
                        + '<td class="xfqg_td10" >' + discountPrice + '</td>'
                        + '<td class="xfqg_td11">' + '<div class="numberbar"><span onclick="number_decrease(this)" class="number_decrease">-</span><span onclick="number_increase(this)" class="number_increase">+</span><input id="Smallplan" maxlength="5" type="text" class="num_text Numberwo" value="'+product_count+'"></div>'+ '</td>'
                        + '<td class="xfqg_td12">' + data.unitName + '</td>'
                        + '<td class="xfqg_td13">' + subtotal + '</td>'
                        /* + '<td class="xfqg_td14">' + '<input class="workinput wicon input-text radius"  type="text" placeholder="要求到货时间" readonly />' + '</td>'
                         + '<td class="xfqg_td15">' + '<input class="workinput wicon input-text radius"  value="" type="text" placeholder="要求采购时间" readonly>' + '</td>'*/
                        + '<td class="xfqg_td16">' + '<input value="1"/>' + '</td>'
                        + '<td class="xfqg_td18"><span></span></td>'  //报价说明
                        + '<td class="rfqg_td18"></td>'//异常询价
                        + '<td class="rfqg_td18"></td>'//异常询价备注
                    a++;
                    html+= '<td class="xfqg_td17 exist" info_state="10">'
                        +'<a class="delProduct" onclick="deleteData(1,this)" href = "javascript:void(0);">删除</a></td>';
                    // '<a  class="matchProduct" onclick="matchProduct(1,this)"' +
                    /*' href="javascript:void(0);">匹配商品</a>' +*/
                    // '<a class="delProduct" onclick="deleteData(1,this)" href = "javascript:void(0);">删除</a></td>'
                    html+= '</tr>';

                    $('#productList').append(html);
                    /*timeSet($('.xfqg_td14>input'));
                    timeSet($('.xfqg_td15>input'));*/
                } else if (oper == 'match') {//匹配
                    console.log('匹配')
                    $('#productList tr').each(function (index,dom) {
                        if($(dom).find('.xfqg_td1').text()==order){
                            // 保留的数据   序号   商品名称  订货要求  要求到货时间   要求采购时间 到货周期
                            var product_name = $(dom).find('td.xfqg_td3').text();
                            var order_fillrates = $(dom).find('td.xfqg_td8').text();
                            if( $(dom).find('.xfqg_td14').children().length>0 ) {
                                var claim_arrival_time = $(dom).find('td.xfqg_td14 input').val();
                            }else{
                                var claim_arrival_time = $(dom).find('td.xfqg_td14').text();
                            }
                            if($(dom).find('.xfqg_td15').children().length>0){
                                var claim_purchase_time = $(dom).find('td.xfqg_td15 input').val();
                            }else{
                                var claim_purchase_time = $(dom).find('td.xfqg_td15').text();
                            }
                            if($(dom).find('.xfqg_td16').children().length>0){
                                var product_cycle = $(dom).find('td.xfqg_td16 input').val();
                            }else{
                                var product_cycle = $(dom).find('td.xfqg_td16').text();
                            }
                            if(product_cycle<=0||!product_cycle){
                                product_cycle=1;
                            }
                            html += '<tr id="' + skuOrder + '" belong_inquiry_id="' + inquiry_id + '">'
                                + '<td class="xfqg_td1">' + order+ '</td>'
                                + '<td class="xfqg_td2" sku_id="' + data.skuId + '" spu_id="' + data.spuId + '">' + data.skuCode + '</td>'
                                + '<td class="xfqg_td3">' + product_name + '</td>'
                                + '<td class="xfqg_td4">' + data.skuName +' </td>'
                                + '<td class="xfqg_td5">' + data.categoryName + '</td>'
                                + '<td class="xfqg_td6">' + data.brandName + '</td>'
                                + '<td class="xfqg_td7">' +'<img style = "width:24px;height:auto;" src ="'+img_url+'"/>'+ data.skuName + '</td>'   //商品描述
                                + '<td class="xfqg_td8">' + order_fillrates + '</td>'   //订货要求
                                + '<td class="xfqg_td9" ></td>'                         //成本价
                                + '<td class="xfqg_td10" >' + discountPrice + '</td>'   //价格
                                + '<td class="xfqg_td11">' +'<div class="numberbar"><span onclick="number_decrease(this)" class="number_decrease">-</span><span onclick="number_increase(this)" class="number_increase">+</span><input id="Smallplan" maxlength="5" type="text" class="num_text Numberwo" value="'+product_count+'"></div>' + '</td>'      //数量
                                + '<td class="xfqg_td12">' + data.unitName + '</td>'  //单位
                                + '<td class="xfqg_td13">' + subtotal + '</td>'   //小计
                                /*            + '<td class="xfqg_td14">' + claim_arrival_time+ '</td>'
                                            + '<td class="xfqg_td15" created_time="' + data.created_time + '" update_time="' + data.update_time + '">' + claim_purchase_time + '</td>'*/
                                + '<td class="xfqg_td16">' +'<input value="'+product_cycle+'">'+ '</td>'
                                + '<td class="xfqg_td18"><span></span></td>'  //报价说明
                                + '<td class="xfqg_td18"><span></span></td>'  //异常询价
                                + '<td class="xfqg_td18"><span></span></td>';  //异常询价备注
                            /* if (data.spu_id==0){
                                 b++
                                 if (data.sku_code!=''){
                                     c++
                                     html+= '<td class="xfqg_td17 presale" info_state="10">' +
                                         '<a class="matchProduct" href="javascript:void(0);">匹配商品</a>' +
                                         '<a class="delProduct" onclick="deleteData(3,this)" href =' +
                                         ' "javascript:void(0);">删除</a></td>'
                                 } else {
                                     html+= '<td class="xfqg_td17 temporary" info_state="10">' +
                                         '<a class="matchProduct" href="javascript:void(0);">匹配商品</a>' +
                                         '<a class="delProduct" onclick="deleteData(2,this)" href =' +
                                         ' "javascript:void(0);">删除</a></td>'
                                 }
                             } else {*/
                            html+= '<td class="xfqg_td17 exist" info_state="10">' +
                                '<a  class="matchProduct" onclick="matchProduct(1,this,'+val+')"'
                                +'<a class="delProduct" onclick="deleteData(1,this)" href = \' +\n' +
                                '                                        \'"javascript:void(0);">删除</a></td>';
                            /*' href="javascript:void(0);">匹配商品</a>' +*/
                            /*'<a class="delProduct" onclick="deleteData(1,this)" href = ' +
                            '"javascript:void(0);">删除</a>*/
                            // }
                            html+= '</tr>'
                            $(dom).replaceWith(html);
                            /* timeSet($('.xfqg_td14>input'));
                             timeSet($('.xfqg_td15>input'));*/
                        }
                    })
                    if (val==2){
                        b--;
                        a++
                    } else if(val==3) {
                        c--;
                        a++
                    }
                }
            }
            btnShow()
        },
        error:function(data){
            alert(data);
        }
    });
}
function goNextPage(title, url) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
// 修改完成
var isUpdate = false;
var bool = true;
$('#save').click(function(){
    if(isUpdate){
        return true;
    }
    var info=[];
    var all_number=0;
    var exist_price_number=0;
    //效验商品编码是否重复&平台商品名称+商品描述是否存在相同条目
    verificationall=true
    commodityCode()
    if(verificationall==false){
        bool = false;
    }else {
        bool = true;
    }

    if (!bool) {
        return false;
    }



    for(var i =0; i<$('#productList>tr').length;i++){
        var item= $($('#productList>tr')[i]);
        console.log(item);
        if((item.find('td.xfqg_td2').attr('sku_id')&&item.find('td.xfqg_td2').attr('sku_id')!=0&&item.find('td.xfqg_td17').attr('info_state')=='10')||(item.find('td.xfqg_td10 input').val()!=''&&item.find('td.xfqg_td10 input').val()!='0'&&item.find('td.xfqg_td17').attr('info_state')=='10')){
            exist_price_number++;
            //判断到货周期是否已填写，并且必须是正整数
            //到货周期
            if( item.find('td.xfqg_td16').children().length>0 ){
                var product_cycle = item.find('td.xfqg_td16 input').val();
            }else{
                var product_cycle = item.find('td.xfqg_td16').text();
            }
            var reg = /^\+?[1-9][0-9]*$/;
            if (!reg.test(product_cycle)) {
                bool = true;
                layer.msg('到货周期为必填，且是正整数', {icon: 5, time: 1000});
                return false;
            }
        }
        if(item.find('td.xfqg_td17').attr('info_state')=='10'){
            all_number++;
        }

        var pic = item.find('.xfqg_td7 img').attr('src');
        var desc = item.find('.xfqg_td7').text();
        var product_depict = JSON.stringify({"pic":pic,"desc":desc});
        //平台商品名称
        if( item.find('td.xfqg_td4').children().length>0 ){
            var sku_name = item.find('td.xfqg_td4 input').val();
        }else{
            var sku_name = item.find('td.xfqg_td4').text();
        }
        //分类
        if( item.find('td.xfqg_td5').children().length>0 ){
            var product_classify= item.find('td.xfqg_td5 input').val();
        }else{
            var product_classify= item.find('td.xfqg_td5').text();
        }
        //品牌
        if( item.find('td.xfqg_td6').children().length>0 ){
            var brand = item.find('td.xfqg_td6 input').val();
        }else{
            var brand = item.find('td.xfqg_td6').text();
        }
        //成本价
        if( item.find('td.xfqg_td9').children().length>0 ){
            var price= item.find('td.xfqg_td9 input').val();
        }else{
            var price = item.find('td.xfqg_td9').text();
        }
        //价格
        if( item.find('td.xfqg_td10').children().length>0 ){
            var discount_price = item.find('td.xfqg_td10 input').val();
        }else{
            var discount_price = item.find('td.xfqg_td10 ').text();
        }
        //单位
        if( item.find('td.xfqg_td12').children().length>0 ){
            var unit_name=item.find('td.xfqg_td12 input').val();
        }else{
            var unit_name=item.find('td.xfqg_td12').text()
        }
        //要求到货时间
        if( item.find('td.xfqg_td14').children().length>0 ){
            var claim_arrival_time = item.find('td.xfqg_td14 input').val();
        }else{
            var claim_arrival_time = item.find('td.xfqg_td14').text();
        }
        //要求采购时间
        if( item.find('td.xfqg_td15').children().length>0 ){
            var claim_purchase_time = item.find('td.xfqg_td15 input').val();
        }else{
            var claim_purchase_time = item.find('td.xfqg_td15').text();
        }
        //到货周期
        if( item.find('td.xfqg_td16').children().length>0 ){
            var product_cycle = item.find('td.xfqg_td16 input').val();
        }else{
            var product_cycle = item.find('td.xfqg_td16').text();
        }
        var obj = {
            id: item.attr('id')||'0',
            belong_inquiry_id: inquiry_id,
            sku_id: item.find('td.xfqg_td2').attr('sku_id'),
            spu_id: item.find('td.xfqg_td2').attr('spu_id'),
            sku_code: item.find('td.xfqg_td2').text(),
            product_name: item.find('td.xfqg_td3').text(),
            sku_name:sku_name ,
            product_classify:product_classify ,
            brand:brand ,
            product_depict: product_depict,
            order_fillrates: item.find('td.xfqg_td8').text(),
            price:price ,
            discount_price: discount_price,
            product_count: item.find('td.xfqg_td11 input').val(),
            unit_name: unit_name, //单位
            subtotal: item.find('td.xfqg_td13').text(),
            claim_arrival_time:claim_arrival_time ,
            claim_purchase_time:claim_purchase_time ,
            product_cycle: product_cycle,
            info_state:item.find('td.xfqg_td17').attr('info_state'),
            explanation:item.find('td.xfqg_td18').text()
        };
        info.push(obj);

    };
    var orderProductsParams = {
        "async": true,
        "crossDomain": true,
        "url": root.xunjiadan.orderCheckUpdate,
        "method": "POST",
        "headers": {"Content-Type": "application/json"},
        "data": JSON.stringify({
            "manage":{
                "inquiry_id":inquiry_id,
                "all_number":all_number,
                "exist_price_number":exist_price_number,
                "inquiry_name" :"" ,
                "customer_id" :"",
                "customer_name" :"",
                "member_id" :"",
                "linkman" :"",
                "linkman_phone" :"",
                "receiver_province" :"" ,
                "receiver_province_name" :"" ,
                "receiver_city" :"",
                "receiver_city_name" :"",
                "receiver_area" :"",
                "receiver_area_name" :"",
                "detail_address" :"",
                "inquiry_status" :"",
                "back_reason" :"",
                "other_explain" :"",
                "inquiry_time" :"",
                "matcher_id" :"",
                "matching_name" :"",
                "matching_time" :"",
                "fix_price_id" :"",
                "fix_price_name" :"",
                "fix_price_time" :"",
                "claim_arrival_time":  $('#timemin').val(),
                "claim_purchase_time":$('#timemax').val()
            },
            "info":info
        })
    }
    $.ajax(orderProductsParams).done(function (response) {
        //console.log(response);
        if(response.code=='0'){
            isUpdate = true;
            layer.msg('询价单修改成功！', {icon: 6,time:1000});
            setTimeout(function () {
                location.reload();
            },1000)
        }else{
            layer.msg(response.message, {icon: 5, time: 1000});
            bool = true;
        }

    });
});
/* $('#packAll').click(function () {
     sessionStorage.setItem("inquiry_id",inquiry_id);
     sessionStorage.setItem("inquiry_status",30);
     //console.log($(window.parent.parent.document))
     $(window.parent.parent.document).find("#replaceOrder")[0].click();
 });*/
/* $('#existGoods').click(function () {
     sessionStorage.setItem("inquiry_id",inquiry_id);
     sessionStorage.setItem("inquiry_status",10);
     //console.log($(window.parent.parent.document))
     $(window.parent.parent.document).find("#replaceOrder")[0].click();
 });*/
/*$('#onlyPreSale').click(function () {
    sessionStorage.setItem("inquiry_id",inquiry_id);
    sessionStorage.setItem("inquiry_status",20);
    //console.log($(window.parent.parent.document))
    $(window.parent.parent.document).find("#replaceOrder")[0].click();
});*/
//商品数量
// 减数量
function number_decrease(el) {
    var num =$(el).next().next().val(); //当前数量
    if (num>1){
        if($(el).parents('td').prev('td').children().length>0){
            var price = parseFloat($(el).parents('td').prev('td').find('input').val())||0;
        }else{
            var price = parseFloat($(el).parents('td').prev('td').text())||0; //单价
        }
        $(el).next().next().val(parseInt(num)-1);
        if(price ==''){
            return false;
        }
        $(el).parents('tr').find('.xfqg_td13').text((price*(parseInt(num)-1)).toFixed(2));
    }else{
        layer.msg('已是最小值', {icon: 5,time:1000});
    }
}

// 加数量
function number_increase(el) {
    var num =$(el).next().val(); //当前数量
    if(num<99999){
        if($(el).parents('td').prev('td').children().length>0){
            var price = parseFloat($(el).parents('td').prev('td').find('input').val())||0;
        }else{
            var price = parseFloat($(el).parents('td').prev('td').text())||0; //单价
        }
        $(el).next().val(parseInt(num)+1);
        if(price == ''){
            return false;
        }
        $(el).parents('tr').find('.xfqg_td13').text((price*(parseInt(num)+1)).toFixed(2));
    }else{
        layer.msg('已是最大值', {icon: 5,time:1000});
    }
}
//商品数量输入框
$('#productList').on('input propertychange','.xfqg_td11 input',function () {
    var product_count  = $(this).val();
    if(product_count==''){
        layer.msg('数量为必填！', {icon: 5,time:1000});
        $(this).val(1);
    }
    var reg = /^\+?[1-9][0-9]*$/;
    if(!reg.test(product_count)){
        layer.msg('数量为正整数！', {icon: 5,time:1000});
        $(this).val('1')
    }
    if(product_count>99999){
        layer.msg('数量不能大于99999！', {icon: 5,time:1000});
        $(this).val(99999);
    }
    // 小计
    if($(this).parents('td').prev('td').children().length>0){
        var price = parseFloat($(this).parents('td').prev('td').find('input').val())||0;
    }else{
        var price = parseFloat($(this).parents('td').prev('td').text())||0; //单价
    }
    if(price == ''){
        return false;
    }
    var num = parseInt($(this).val());
    $(this).parents('tr').find('.xfqg_td13').text((price*num).toFixed(2));
})
//商品价格输入框
function checkPrice(el){
    console.log($(el).val())
    var reg = /^[0-9]+(.[0-9]{1,2})?$/;
    if(!reg.test($(el).val())||$(el).val()=='0'){
        layer.msg('请输入大于0的数字,且最多能有两位小数！', {icon: 5,time:1000});
        $(el).val('');
        $(el).parents('tr').find('.xfqg_td13').text('');
        return false;
    }
    //小计
    var num = parseInt($(el).parents('tr').find('.xfqg_td11 input').val());
    $(el).parents('tr').find('.xfqg_td13').text((num*parseFloat($(el).val()).toFixed(2)));
}
//时间日期初始化
function timeSet(ele) {
    ele.each(function (index,dom) {
        $.jeDate(dom,{
            format:"YYYY-MM-DD hh:mm:ss"
        });
    });

}
//到货齐发 临采 现货商品
function daohuo(val) {
    var startss=""
    if(val==1){
        startss="10"
    }else if(val==2){
        startss="20"
    }else if(val==3){
        startss="30"
    }

    var objA=[]
    var jsoni={
        inquiry_id:inquiry_id+','+JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name+','+JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
        classify:startss
    };
    objA.push(jsoni);
    $.ajax({
        url: root.replaceInter.replace_inquiryDisposeTake,
        cache: false, //禁用缓存
        type: "POST",
        data: jsoni,
        success: function (data) {
            if(data.code==0){
                $.Huimodalalert("下推成功！",2000);
            }else {
                $.Huimodalalert(data.message,2000);
            }


        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

var len
var Preser
var common=8//要限制输入的字数
function checkMaxIut(me) {
    var text=$(me).val()
    strlen(text)
    if(len>common){
        $(me).val(Preser)
    }else {
        Preser=$(me).val()
    }
}
function strlen(str){
    len = 0;
    for (var i=0; i<str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
            len++;
        } else {
            len+=2;
        }
    }
    return len;
}
//操作日志
function operationlog() {
    sessionStorage.setItem("inquiry_id",inquiry_id)
    var title="操作日志"
    var url="operationLog.html"
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
function commodityCode() {
    //效验商品编码是否重复&平台商品名称+商品描述是否存在相同条目
    var productList = $('#productList tr');
    var maop=[]
    var plm={}
    var codeids=[]
    for(var j=0;j<productList.length;j++) {

        if ($(productList[j]).find('.rfqg_td7 input').val() != undefined && $(productList[j]).find('.xfqg_td4 input').val() != undefined){
            plm = {
                "name": $(productList[j]).find('.xfqg_td7 input').val() +","+ $(productList[j]).find('.xfqg_td4 input').val()+","+$(productList[j]).find('.xfqg_td1').text(),

            }
        }else {

            if($(productList[j]).find('.xfqg_td4 ').text()==""){
                plm = {
                    "name": $(productList[j]).find('.xfqg_td7 ').text() +","+ $(productList[j]).find('.xfqg_td4 input').val()+","+$(productList[j]).find('.xfqg_td1').text(),
                }
            }else {
                plm = {
                    "name": $(productList[j]).find('.xfqg_td7 ').text() +","+ $(productList[j]).find('.xfqg_td4 ').text()+","+$(productList[j]).find('.xfqg_td1').text(),
                }
            }

        }
        if($(productList[j]).find('.xfqg_td17').attr("info_state")==10){
            maop.push(plm)
            codeids.push($(productList[j]).find('.xfqg_td2').text()+","+$(productList[j]).find('.xfqg_td1').text())
        }
    }

    var repeats=""
    var repeatcodes=""
    //判断code码
    $.each(codeids,function(k,fircode){
        $.each(codeids,function(h,sedcode) {
            if (k==h){
                return true;
            }
            if(fircode.split(',')[0]!=""){
                if (fircode.split(',')[0]==sedcode.split(',')[0]) {
                    var repeatcode='第<span>'+fircode.split(',')[1]+'</span>行:<span>'+fircode.split(',')[0]+'</span>'
                    repeatcodes+=repeatcode+","
                    var curInd2 = layer.confirm('商品编码重复！（'+repeatcodes+')', {title:'提示',btn: ['确定']}, function(index){
                        layer.close(curInd2);
                    },function(){
                        layer.close(curInd2);

                    });
                    verificationall = false;
                    return false;
                }

                addintercepts=0
            }else {
                addintercepts=1

            }

        })
    })
    if(addintercepts==1){
        repeats=''
        //判断平台商品名称+商品描述
        $.each(maop,function(i,first){
            $.each(maop,function(s,sed){
                if (i==s){
                    return true;
                }
                var fiestname=first.name.split(',')[0]+first.name.split(',')[1]
                var sedname=sed.name.split(',')[0]+sed.name.split(',')[1]
                if(fiestname!=""||sedname!=""){
                    if (fiestname==sedname){
                        if(first.name.split(',')[1]!=""&&first.name.split(',')[0]!=""){
                            var repeat='第<span>'+first.name.split(',')[2]+'</span>行:<span>'+first.name.split(',')[1]+'</span>+<span>'+first.name.split(',')[0]+'</span>'
                            if(repeat!=""){
                                repeats+=repeat+","
                                var curInd = layer.confirm('平台商品名称+商品描述存在相同条目！（'+repeats+')', {title:'提示',btn: ['确定']}, function(index){
                                    layer.close(curInd);
                                },function(){
                                    layer.close(curInd);

                                });
                                verificationall = false;
                                return false;
                            }
                        }


                    }

                }

            })
        })
    }
}